package com.suma.boot.mybatis.page;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.github.pagehelper.PageHelper;

/**
 * @author chenqi
 * @time 2017/8/22
 */
@Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@EnableConfigurationProperties({ MybatisProperties.class, MybatisPageHelperProperties.class })
public class MybatisPageHelperConfiguration {

	@Autowired
	private MybatisProperties mybatisProperties;

	@Bean
	@ConditionalOnMissingBean
	public DataSource dataSource() {
		if (mybatisProperties.getTypeAliasesPackage() == null || mybatisProperties.getMapperLocations().length <= 0) {
			return null;
		}
		return DruidDataSourceBuilder.create().build();
	}

	@Bean
	@Primary
	@ConditionalOnClass(DataSource.class)
	public SqlSessionFactory sqlSessionFactory(DataSource dataSource, MybatisPageHelperProperties pagerHelperProperties) throws Exception {
		SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
		fb.setDataSource(dataSource);
		fb.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackage());
		fb.setMapperLocations(mybatisProperties.resolveMapperLocations());
        fb.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
		fb.setPlugins(new Interceptor[] { this.preparePagerPlugin(pagerHelperProperties) });
		return fb.getObject();
	}

	private PageHelper preparePagerPlugin(MybatisPageHelperProperties pagerHelperProperties) {
		PageHelper pageHelper = new PageHelper();
		Properties props = new Properties();
		props.setProperty("dialect", pagerHelperProperties.getDialect());
		props.setProperty("reasonable", pagerHelperProperties.getReasonable());
		props.setProperty("supportMethodsArguments", pagerHelperProperties.getSupportMethodsArguments());
		props.setProperty("returnPageInfo", pagerHelperProperties.getReturnPageInfo());
		props.setProperty("params", pagerHelperProperties.getParams());
		pageHelper.setProperties(props);
		return pageHelper;
	}
}
